/*本页面不要使用Jquery*/

var pageX = {
        MAX_INPUT_LENGTH : 2000,
        actionType : "",//记录当前提交类型
        wfDesigner : null,
        currentAction : null,
        isLoading : false,
        attObj : null,
        cache : {
            "postData" : {
                "fileUrlIds":[], "fileJson" : "[]"
            },
            "tempAtt" : null,
            "isSubmitting" : false,//防止重复提交
            "noteList" : []//提交成功后，的提示信息
        },
        exeLock : false
}

var _pageObj = {};
var _storge_key = "";
var dataArea = "#mainBodyArea";

//操作和流程锁映射关系
var ACTION_LOCK_CODE = {
    "Return": WorkFlowLock.STEP_BACK,//回退
    "Terminate": WorkFlowLock.STEP_STOP,//终止
    "Cancel": WorkFlowLock.REPEAL_ITEM,//撤销
    "SpecifiesReturn": WorkFlowLock.SPECIFIES_RETURN,// 指定回退
    "Transfer": WorkFlowLock.TRANSFER,// 移交
    "Edit": WorkFlowLock.EDIT_CONTENT//修改正文
}

var actionI18n = {};


//重写cmp的loading组件
var cmpLoading = cmp.dialog.loading;
cmp.dialog.loading = function(status){
    
    if(status === false){
        pageX.isLoading= false;
        cmpLoading.apply(cmp.dialog, arguments);
    }else{
        if(pageX.isLoading !== true){
            cmpLoading.apply(cmp.dialog, arguments);
        }
        pageX.isLoading= true;
    }
}

var isWfLoaded=false;
var isFormLoaded=false;

cmp.ready(function() {// 缓存详情页面数据
    
    _storge_key = CollCacheKey.summary.comment;
    
    _initBackEvent();
    cmp.i18n.init(_collPath + "/i18n/", "Collaboration", function(){
        
        
        actionI18n = {
                "Forward" : cmp.i18n("collaboration.page.lable.button.forward"),//转发协同
                "Return" : cmp.i18n("collaboration.page.lable.button.return"),//回退
                "Terminate" : cmp.i18n("collaboration.page.lable.button.terminate"),//终止
                "Cancel" : cmp.i18n("collaboration.page.lable.button.cancel1"),//撤销
                "SpecifiesReturn" : cmp.i18n("collaboration.default.stepBack"),// 指定回退
                "Transfer" : cmp.i18n("collaboration.page.lable.button.transfer")// 移交
                //"Edit" : cmp.i18n("collaboration.page.lable.button.modifyContent")//修改正文 屏蔽M3修改策略在处理界面的显示
        }
        
        _initPageData(function(){
            
            _fillPage();
            
            document.addEventListener('beforepageredirect', function(e){ 
                _storePageObj();
            });
            
            //清空缓存
            document.addEventListener('deletesessioncache', function(e){
               try{
                    //删除协同缓存
                   CollCacheKey.delCacheKeys(CollCacheKey.summary, pageX.winParams.cache_subfix);
                    
                    var options = { 
                            moduleId:summaryBO["summary"].id,
                            rightId:summaryBO["summary"].rightId,
                            viewState: summaryBO._viewState
                    }
                    cmp.sui.clearCache(options);
                    
                    //刷新协同列表
                    setListViewRefresh("true");
                    
                  //触发刷新壳数据
                    cmp.webViewListener.fire({ 
                        type: 'com.seeyon.m3.ListRefresh', 
                        data: {affairid: summaryBO["summary"].affairId}
                    });
                }catch(e){}
            });
            
            cmp.HeaderFixed("#hid", document.querySelector("#content"));
            cmp.description.init(document.querySelector("#content"));
        });
    });
});

/*** 开始 ***/

function _fillPage(){
    
    var pageTitle = pageX.winParams.title || cmp.i18n("collaboration.page.lable.button.deal");
    _$("title").innerText = pageTitle
    _$("#title").innerText = pageTitle;
    _$("#content").setAttribute("placeholder", pageX.winParams.placeholder 
                                              || summaryBO.nodeDesc 
                                              || cmp.i18n("collaboration.page.info.inputOpinion"));

    //创建动态dom
    _creatDoms();
    
    //处理按钮展现
    _initDealBtns();
    
    //装载数据
    CollUtils.fillDom(dataArea, pageX.cache.datas);
    
    //初始化开关
    var swContainer = _$("#switch_container");
    _initSwitch("hide", pageX.cache.postData.hide, swContainer);
    _initSwitch("tracking", pageX.cache.postData.tracking, swContainer);
    _initSwitch("Archive", pageX.cache.postData.Archive, swContainer);
    
    //加载附件相关信息
    loadAttachment();
    
    //装载点赞
    _initLike();
    
    //装载常用语
    _initCommonPhrase();
    
    //加载意见框
    _initContent();
    
    //操作按钮显示
    var $allBtns = _$("#allBtns"), 
        btns = ["#attachment_btn", "#likeBtn", "#phrasesBtn", "#atBtn"];
    for(var i = 0; i < btns.length; i++){
        var btn = _$(btns[i], false, $allBtns);
        if(btn && !btn.classList.contains("display_none")){
            $allBtns.classList.toggle("display_none");
            break;
        }
    }
    
    /*if(pageX.winParams.action == WorkFlowLock.SUBMIT
            || pageX.winParams.action == WorkFlowLock.SPECIFIES_RETURN){*/
        
    _initWfDesigner({
        stepBackToTargetNode:function(theStepBackNodeId, submitStyle, isCircleBack, isWFTrace){
            exeSubmitData("actionStepBackToTargetNode", theStepBackNodeId, submitStyle, isCircleBack, isWFTrace);
        }
    },{
        model : "silent",//采用静默模式
        onTriggerEdit : function(){
            var c = _$("#workflow_dot").classList;
            if(c.contains("display_none"))
                c.remove("display_none");
        },
        finishWfData: function(){
            isWfLoaded=true;
            if(isFormLoaded){
                //数据加载完成后执行续办提交
                _backFromContinue();
            }
        }
    });//加载流程数据
    
    /*}*/
    
    if(pageX.cache.isSubmitting){
        cmp.notification.toast(cmp.i18n("collaboration.action.alreadySubmit"),"center");
    }
}

/**
 * 动态创建元素
 */
function _creatDoms(){
    
    //加载操作和开关
    _initActions();
    
    //加载态度
    _initAttitude();
}

/**
 * 初始化处理按钮
 */
function _initDealBtns(){

    var subState = summaryBO["summary"].affairSubState;
    
    if(pageX.cache.isSubmitting){
        return;
    }
    
    if(pageX.winParams.action == WorkFlowLock.SUBMIT){
        
        //指定回退状态
        if(subState != "17" && subState != "15"){
            
            var $zcdbBtn;
            
            if(summaryBO["currentPolicy"].id == "newsaudit"  
                || summaryBO["currentPolicy"].id == "bulletionaudit"){
                
                _$("#news_submitBtn").classList.remove("display_none");
                _$("#news_noPassBtn").classList.remove("display_none");
                
                cmp.event.click(_$("#news_submitBtn"), function(){
                    exeSubmitData("actionSubmit")
                });
                cmp.event.click(_$("#news_noPassBtn"), function(){
                    exeSubmitData("actionTerminateSummary");
                });
                
                $zcdbBtn = _$("#news_zcdbBtn");
                
                _$("#submitBtn").remove();
                _$("#zcdbBtn").remove();
            }else{
                
                _$("#news_zcdbBtn").remove();
                _$("#news_submitBtn").remove();
                _$("#news_noPassBtn").remove();
                
                $zcdbBtn = _$("#zcdbBtn");
                
                var submitLable = "";
              //审核节点 ||核定节点
                if(summaryBO["currentPolicy"].id=="formaudit" || summaryBO["currentPolicy"].id=="vouch"){
                    if (summaryBO["currentPolicy"].id=="formaudit") {
                        _$("#auditNoBtn").innerText = cmp.i18n("collaboration.page.lable.button.formaudit")+cmp.i18n("collaboration.page.lable.button.nopass");//审核不通过
                        _$("#auditPassBtn").innerText = cmp.i18n("collaboration.page.lable.button.formaudit")+cmp.i18n("collaboration.page.lable.pass");//审核通过
                    }
                    var $auditNoBtn = _$("#auditNoBtn"),
                        $auditPassBtn = _$("#auditPassBtn");
                    
                    cmp.event.click($auditNoBtn, function(){
                    	if(summaryBO.inInSpecialSB){
                    		_alert(cmp.i18n("collaboration.inSb.cannotsb"));
                    		return;
                    	}
                        exeSubmitData("actionReturnSummary"); //不通过走回退逻辑
                    });
                    cmp.event.click($auditPassBtn, function(){
                        exeSubmitData("actionSubmit"); //通过走提交逻辑
                    });
                    $auditNoBtn.classList.remove("display_none");
                    $auditPassBtn.classList.remove("display_none");
                    $zcdbBtn.style.width = "30%";
                    $zcdbBtn.style.marginRight = "5px";
                    
                }else {
                    if(summaryBO["summary"].showCustomDealWith=="true" && summaryBO["summary"].customDealWith=="true" && subState!= "16"){//有续办权限，subState!= "16"判断指定回退选择“直接提交给我”时，不能进行续办操作
                        _$("#submitBtn").addEventListener("tap", _continueDo);
                        _$("#submitBtn").classList.remove("display_none");
                    }else{
                        _$("#submitBtn").addEventListener("tap", _doSubmit);
                        _$("#submitBtn").classList.remove("display_none");
                    }
                }
            }
            
            //暂存待办
            if(_hasPermissions(summaryBO.pageConfig.nodeActions, "Comment") && subState != "16"){
                $zcdbBtn.classList.remove("display_none");
                $zcdbBtn.addEventListener("tap", _doZcdb);
            }else{
                $zcdbBtn.remove();
            }
        }
    }else{
        
      //重置按钮名称
        _$("#submitBtn").innerText = cmp.i18n("collaboration.page.lable.button.submit");
        
        //TODO 根据实际情况绑定不同的事件
        var actionName = "";
        if(pageX.winParams.action == WorkFlowLock.STEP_BACK)
            actionName = "actionReturnSummary";
        else if(pageX.winParams.action == WorkFlowLock.REPEAL_ITEM)
            actionName = "actionRepealSummary";
        else if(pageX.winParams.action == WorkFlowLock.STEP_STOP)
            actionName = "actionTerminateSummary";
        else if(pageX.winParams.action == WorkFlowLock.SPECIFIES_RETURN)
            actionName = "actionStepBackToTargetNode";
        else if(pageX.winParams.action == WorkFlowLock.TRANSFER)
            actionName = "actionTransferSummary";
            
        cmp.event.click(_$("#submitBtn"), function(){
            exeSubmitData(actionName);
        });
        
        _$("#submitBtn").classList.remove("display_none");
        
    }
}

/**
 * 加载意见框
 */
function _initContent(){
    
    var $content = _$('#content');
    
  //是否有意见框
    if(_hasPermissions(summaryBO.pageConfig.nodeActions, "Opinion")){
        
        function showContentCount(){
            CollUtils.fnFontCount("#content", "#fontCount", pageX.MAX_INPUT_LENGTH);
        }
        $content.addEventListener('input', showContentCount);
        showContentCount();
        
        //TODO 是否根据情况加载at功能
        _initAtWho();
        
        _$("#comment_div").classList.remove("display_none");
        _$("#fontCount").classList.remove("display_none");
        
       // 40为常用语这一行的高度
        // $content.style.height = (_$("#comment_div").scrollHeight - 40) + "px";
    }else{
        $content.value = "";
    }
}

/**
 * 加载常用语
 */
function _initCommonPhrase(){
    
  //常用语
    if(_hasPermissions(summaryBO.pageConfig.nodeActions, "Opinion") 
            && _hasPermissions(summaryBO.pageConfig.nodeActions, "CommonPhrase")){
        
        var $phrasesBtn = _$("#phrasesBtn"); 
        $phrasesBtn.classList.remove("display_none");
        
        $s.CommonPhrase.phrases({}, errorBuilder({
            success : function(result) {
                if(result && result.length > 0){
                    _$("#phrases_ul").innerHTML = cmp.tpl(_$("#phrases_template").innerHTML, result);
                    cmp("#phrases_ul").on("tap", "li", function(){
                        _$("#content").value = CollUtils.getTextDealComment("#content") + this.innerHTML;
                        _switchPhrases();
                        CollUtils.fnFontCount("#content", "#fontCount", pageX.MAX_INPUT_LENGTH);
                    });
                }
            }
        }));
        
        var phrases_container = _$('#phrases_container');
        var header = phrases_container.querySelector('header');
        var navLeft = phrases_container.querySelector('#phrase_goback');
        var phrases_div = _$('#phrases_div');
        
        phrases_div.style.height = phrases_container.offsetHeight-header.offsetHeight+"px";
        
        //点击常用语
        $phrasesBtn.addEventListener('tap',function(){
            _switchPhrases();
        });
       
        //点击常用语弹出容器的回退按钮
        navLeft.addEventListener('tap',function(){
            _switchPhrases();
        });
    }
}

//常用语切换
function _switchPhrases(phrases_container){
    phrases_container = phrases_container || _$('#phrases_container');
    if(phrases_container.classList.contains('cmp-active')){
        phrases_container.classList.remove('cmp-active');
        cmp.backbutton.pop();
    }else{
        cmp.backbutton.push(_switchPhrases);
        phrases_container.classList.add('cmp-active');
        _$('#phraser').style.display = 'block';
    }
}

/**
 * 加载点赞
 */
function _initLike(){
    
    if(summaryBO["summary"].canPraise && _hasPermissions(summaryBO.pageConfig.nodeActions, "Opinion")){
        
        var likeBtn = _$("#likeBtn");
        
        if(pageX.cache.postData.likeSummary){
            likeBtn.classList.add("blue-color");
        }
        likeBtn.classList.remove("display_none");
        
        likeBtn.addEventListener('tap',function(){
            
            var thisClass = this.classList, method;
            
            if(pageX.cache.postData.likeSummary){
                method = "remove";
            }else{
                method = "add";
            }
            thisClass[method]("blue-color");
            
            pageX.cache.postData.likeSummary = !pageX.cache.postData.likeSummary;
         });
    }
}

/**
 * 初始化附件
 */
function loadAttachment(){
    
    var nodeActions = summaryBO.pageConfig.nodeActions;
        
    var showAuth = "";
    if(CollUtils.isInArray(nodeActions, "UploadAttachment") && CollUtils.isInArray(nodeActions, "UploadRelDoc")){
        showAuth = -1;
    }else if(CollUtils.isInArray(nodeActions, "UploadAttachment")){
        showAuth = 1;
    }else if(CollUtils.isInArray(nodeActions, "UploadRelDoc")){
        showAuth = 2;
    }
    
    var $attBtn = _$("#attachment_btn");
    if(showAuth !=""){
        $attBtn.classList.remove("display_none");
    }
    
    //附件组件
    var initParam = {
        showAuth : showAuth,
        uploadId : "picture",
        handler : "#attachment_btn",
        initAttData : pageX.cache.tempAtt,
        selectFunc : function(result){
            
            pageX.cache.postData.fileJson = cmp.toJSON(result);
            
            //展示附件数量
            _showAttNum(result.length);
        }
    }
    pageX.attObj = new SeeyonAttachment({initParam : initParam});
}

/**
 * 展示附件数量
 */
function _showAttNum(num, $attBtn){
    
    $attBtn = $attBtn || _$("#attachment_btn");
    
    var text = "", color = "#A2ACC7";
    if(num > 0){
        text = num;
        color = "#3aadfb";
    }
    $attBtn.style.color = color;
    _$("#attCount").innerHTML = text;
}


/**
 * 初始化态度
 */
function _initAttitude(){
    var attitudeBtns = [];
    if(summaryBO.pageConfig.attitudeBtns != 3){
        if(summaryBO.pageConfig.attitudeBtns == 1){
            var att_readed = {
                    "lable" : cmp.i18n("collaboration.page.lable.att_readed"),//已阅
                    "value" : "collaboration.dealAttitude.haveRead"
                }
            att_readed.state = pageX.cache.postData["attitude"] == att_readed.value ? "on" : "off";
            attitudeBtns.push(att_readed);
        }
        var att_agree = {
                "lable" : cmp.i18n("collaboration.page.lable.att_agree"),//同意
                "value" : "collaboration.dealAttitude.agree"
            }
        att_agree.state = pageX.cache.postData["attitude"] == att_agree.value ? "on" : "off";
        attitudeBtns.push(att_agree);
        
        var att_disagree = {
                "lable" : cmp.i18n("collaboration.page.lable.att_disagree"),//不同意
                "value" : "collaboration.dealAttitude.disagree"
            }
        att_disagree.state = pageX.cache.postData["attitude"] == att_disagree.value ? "on" : "off";
        attitudeBtns.push(att_disagree);
    }
    if(attitudeBtns.length > 0){
        
        _$("#button_list_nav").innerHTML = cmp.tpl(_$("#attitude_templage").innerHTML, attitudeBtns);
        _$("#button_list_nav").style.display = "block";
        
        var t = 45;
        if(!_$("#specifiesReturn_div").classList.contains("display_none")){
            t += 40;
        }
        _$("#comment_div").style.top = t + "px";
        
        //顶部按钮的切换点击
        cmp("#button_list_nav").on("tap", "li", function(){
            var $input = _$("input", false, this);
            pageX.cache.postData["attitude"] = $input.value;
        });
    }
}

//获取节点权限
function _initActions() {

    if(pageX.cache.isSubmitting){
        return;
    }
    
  var nodeActions = summaryBO.pageConfig.nodeActions;
  var affairSubState = summaryBO["summary"].affairSubState;
  
  var switchs = [];
  
  //处理的时候才有更多选项
  if(pageX.winParams.action == WorkFlowLock.SUBMIT){
      
      if(!summaryBO.isHaveNewColl){
          delete actionI18n["Forward"];
      }
      
      //非当前指定回退状态，整个流程处于指定回退状态
      if(summaryBO.inInSpecialSB){
          delete actionI18n["SpecifiesReturn"];
          delete actionI18n["Return"];
      }else if(affairSubState == '15'){
          
          delete actionI18n["Transfer"];
          delete actionI18n["Return"];
          delete actionI18n["SpecifiesReturn"];
          
      }else if(affairSubState == '16'){
          
          delete actionI18n["Transfer"];
          delete actionI18n["Return"];
          
      }else if(affairSubState == '17'){
          delete actionI18n["Transfer"];
          delete actionI18n["Return"];
          delete actionI18n["SpecifiesReturn"];
      }
      
    //只有office格式的正文才能修改正文且只有CMP壳才能修改正文
      if(!summaryBO.content 
              || !summaryBO.canEditContent
              || summaryBO.content.contentType=="20" 
              || !summaryBO.content.fileId 
              || !CollUtils.isCMPShell() 
      	      || !cmp.os.android){
      	delete actionI18n["Edit"];
      }
      
      for(var i = 0, len = summaryBO.pageConfig.advanceActions.length; i < len; i++){
          var action = summaryBO.pageConfig.advanceActions[i];
          if(actionI18n[action]){
              switchs.push({
                  "code" : action,
                  "lable" : actionI18n[action],
                  "type" : "button"
              });
          }
      }
      
      
      if(affairSubState != "15" 
          && affairSubState != "16" 
              && affairSubState != "17" 
                  && summaryBO["summary"].canModify == 'true'){
          
          //权限校验
          if ( _hasPermissions(nodeActions, "AddNode") 
                  || _hasPermissions(nodeActions, "JointSign")
                  || _hasPermissions(nodeActions, "RemoveNode")
                  || _hasPermissions(nodeActions, "Infom")) {
              
              //工作流相关
              var $wfBtn = _$("#workflow_btn");
              $wfBtn.classList.remove("display_none");
              $wfBtn.addEventListener("tap", function(e){
                  
                  var pageParams = {
                          "cache_subfix" : pageX.winParams.cache_subfix,
                          "WebviewEvent" : WebEvents.M3_EVENT_COMMENT + pageX.winParams.cache_subfix,
                          "edit" : true
                      }
                      
                  cmp.event.trigger("beforepageredirect", document);
                  cmp.href.next(_collPath + "/html/details/workflowEdit.html"+colBuildVersion, pageParams);
              });
          }
      }
  }
  
  //指定回退
  if(pageX.winParams.action != WorkFlowLock.SPECIFIES_RETURN){
      
      //保证这三个按钮的顺序
      
      if (pageX.winParams.action == WorkFlowLock.SUBMIT 
              && _hasPermissions(nodeActions, "Archive") 
              && summaryBO["summary"].canArchive == "1") {
          
          switchs.push({
              "code" : "Archive",
              "lable" : cmp.i18n("collaboration.page.lable.button.archive1"),//归档
              "type" : "switch"
          });
      }
      
    //OA-100366
      var isFormFieldOption = false;
      if(summaryBO["summary"].bodyType == "20"){
          isFormFieldOption = cmp.sui.hasEditRightOfFlowDealOption();
      }
      if (_hasPermissions(nodeActions, "Opinion") && !isFormFieldOption) {
          switchs.push({
              "code" : "hide",
              "lable" : cmp.i18n("collaboration.page.lable.hideComment"),// 隐藏意见
              "type" : "switch"
          });
      }
      if (_hasPermissions(nodeActions, "Track")) {
          switchs.push({
              "code" : "tracking",
              "lable" : cmp.i18n("collaboration.page.lable.button.track"),//跟踪
              "type" : "switch"
          });
      }
      
  }else{
      var $specialDiv = _$("#specifiesReturn_div"); 
      //指定回退已选择:{0}
      $specialDiv.innerText =  cmp.i18n("collaboration.page.lable.specialSelected", [pageX.winParams.returnInfo.toNodeName]);
      $specialDiv.classList.remove("display_none");
      $specialDiv.addEventListener("tap", function(){
          pageX.wfDesigner.specifiesReturn(function(returnInfo, submitStyleName){
              pageX.winParams.returnInfo = returnInfo;
              _$("#specifiesReturn_div").innerText = cmp.i18n("collaboration.page.lable.specialSelected", [returnInfo.toNodeName]);
              _$("title").innerText = submitStyleName
              _$("#title").innerText = submitStyleName;
          }, pageX.winParams.returnInfo);
      });
  }
  
  if(switchs.length > 0){
      var switchsTemplate = _$("#switch_template").innerHTML;
      var switchsHTML = cmp.tpl(switchsTemplate, switchs);
      _$("#switchs_ul").innerHTML = switchsHTML;
      
      //操作事件
      cmp("#switchs_ul").on("tap", ".menu_btn", _clickMenuBtn);
      
    //开关按钮
      cmp("#switchs_ul .cmp-switch").each(function() { //循环所有toggle

          //触发开关初始化
          cmp(this)["switch"]();
          
          this.addEventListener('toggle', function(event) {
              var tCode = this.getAttribute("switchcode");
              pageX.cache.postData[tCode] = this.classList.contains('cmp-active');
          });
      });
      
      //开关显示
      var $switcheBtn = _$("#switch_pop_btn"); 
      $switcheBtn.classList.remove("display_none");
      $switcheBtn.addEventListener('tap',switcheBtnAddListener);
      
      //影藏开关
      _$("#topPopover").addEventListener('tap', function(e){
          if(e.target == this){
              this.classList.add("display_none");
              _$("#switch_pop_btn").addEventListener('tap',switcheBtnAddListener);
          }
      });
  }
}

function switcheBtnAddListener(){
	  _$("#topPopover").classList.remove("display_none");
	  this.removeEventListener('tap',switcheBtnAddListener);
	  cmp.backbutton.push(function(){});
  }


//单击菜单
function _clickMenuBtn(){
	
	setTimeout(function(){
		_$("#switch_pop_btn").addEventListener('tap',switcheBtnAddListener);
	},1000);
	
	_$("#topPopover").classList.add("display_none");
	var backPop = _$(".cmp-backdrop");
	if(backPop){
	    backPop.remove();
	}
	
	//顺序必须放在下面代码之前
	cmp.backbutton.pop();
	
    var tCode = this.getAttribute("data-code");
    pageX.currentAction = ACTION_LOCK_CODE[tCode];
    switch (tCode) {
    case "Forward":
        exeSubmitData("actionForward");
        break;
    case "Return":
        exeSubmitData("actionReturnSummary");
        break;
    case "Terminate":
        exeSubmitData("actionTerminateSummary");
        break;
    case "Cancel":
        exeSubmitData("actionRepealSummary");
        break;
    case "SpecifiesReturn":
        exeSubmitData("actionSpecifiesReturn");
        break;
    case "Transfer":
        exeSubmitData("actionTransferSummary");
        break;
    case "Edit":
    	_editContent();
        break;
    default:
        break;
    }
}


/**
 * 切换开关
 */
function _initSwitch(code, value, container){
    
    var $switchs = container || _$("#switchs_ul"),
        sw = _$(".cmp-switch[switchcode='" + code + "']", false, $switchs);
    
    if(sw){
        var method, isActive = sw.classList.contains("cmp-active");
        if(isActive != value){
            if(value === true){
                method = "add";
            }else{
                method = "remove";
            }
            sw.classList[method]("cmp-active");
        }
    }
}

//装载数据
function _initPageData(onDataReady) {
    
    pageX.winParams = cmp.href.getParam();
    
    //缓存加载
    window.summaryBO = CollUtils.loadCache(CollCacheKey.summary.summaryBO + pageX.winParams.cache_subfix);
    
    _storge_key = _storge_key + pageX.winParams.cache_subfix;
    var cacheData = CollUtils.loadCache(_storge_key, true);
    pageX.cache = cacheData || pageX.cache;
    
    //缓存不存在
    if(!cacheData){
        
        var nodeActions = summaryBO.pageConfig.nodeActions;
        
        if(_hasPermissions(nodeActions, "Opinion")){
            pageX.cache.postData.hide = !!summaryBO.draftComment.hide;
        }
        if(_hasPermissions(nodeActions, "Track")){
            pageX.cache.postData.tracking = !(summaryBO["trackProcess"] == "false");
        }
        if(_hasPermissions(nodeActions, "Archive") && summaryBO["summary"].canArchive == "1"){
            pageX.cache.postData.Archive = false;
        }
        
        //点赞
        pageX.cache.postData.likeSummary = !!summaryBO.draftComment.likeSummary;
        
        //初始化附件
        pageX.cache.tempAtt = summaryBO.draftComment.attachments;
        
        if(summaryBO.pageConfig.attitudeBtns != 3){
            if(summaryBO.pageConfig.attitudeBtns == 1 && summaryBO.pageConfig.defaultAttitude == 1){
                pageX.cache.postData.attitude = "collaboration.dealAttitude.haveRead";
            }else{
                pageX.cache.postData.attitude = "collaboration.dealAttitude.agree";
            }
        }
        
        pageX.cache.postData.attitude = summaryBO.draftComment.attitude || pageX.cache.postData.attitude;
        pageX.cache.postData.commentId = summaryBO.draftComment.commentId || void 0;
        //初始化进行缓存合并
        pageX.cache.datas = {
                content : summaryBO.draftComment.content || ""
        }
    }
    
    //装载表单数据
    if("20" == summaryBO["summary"].bodyType){
        var optionsCache = {
                moduleId : summaryBO["summary"].id,
                rightId : summaryBO["summary"].rightId,
                viewState: summaryBO._viewState
        }
        cmp.sui.loadFormDataFromCache(optionsCache,function(data){
            if(data.success==true){
                isFormLoaded=true;
                if(isWfLoaded){
                    _backFromContinue();
                }
            }
        });
    }
    
    if(onDataReady){
        onDataReady();
    }
}

//是否显示某个权限
function _hasPermissions(ps, p){
  return CollUtils.isInArray(ps, p);
}

function _initBackEvent(){
	
	cmp.backbutton();
    cmp.backbutton.push(_goBack);
    // _$("#goBackBtn").addEventListener("tap", _goBack);
}

//返回协同详细页面
function _goBackToSummary(){
    var backN = 1;
    if(window.summaryBO && summaryBO.backIndex){
        backN = summaryBO.backIndex;
    }
    _goBack(backN);
}

//返回
function _goBack(n) {
    
  //防止爆点
    if(pageX.exeLock){
        return;
    }
    pageX.exeLock = true;
    
    var backN = 1;
    if(typeof(n)!= 'undefined' && typeof(n) != 'object'){
        backN = n;
    }
    
    if(pageX.winParams.action != WorkFlowLock.SUBMIT){
        WorkFlowDesignerUtil.unLockH5Workflow(summaryBO["summary"].processId, pageX.winParams["action"]);
    }

    summaryBO.backIndex = summaryBO.backIndex - backN;
    cmp.storage.save(CollCacheKey.summary.summaryBO + pageX.winParams.cache_subfix, cmp.toJSON(window.summaryBO), true);
    
    //保留数据
    cmp.event.trigger("beforepageredirect", document);
    cmp.href.back(backN, null,  pageX.winParams.WebviewEvent);
}

//处理成功后返回列表
function _gotoList(){
    
    //触发删除缓存
    cmp.event.trigger("deletesessioncache", document);
    
    var backN = 1;
    if(window.summaryBO && summaryBO.backIndex){
        backN += summaryBO.backIndex;
    }
    cmp.href.back(backN);
}


function _storePageObj(){
    
    //临时附件
    if(pageX.attObj){
        pageX.cache.tempAtt = pageX.attObj.attObjArray;
    }
    
    pageX.cache.datas = CollUtils.formPostData(_$(dataArea));
    cmp.storage.save(_storge_key, cmp.toJSON(pageX.cache), true);
}

function _close(result, formSnMsg){
    
    if(typeof(result)!= 'undefined' && result["error_msg"]){
        _stopSubmitting();
        _alert(result["error_msg"]);
    }else {
        
        var len = pageX.cache.noteList.length, note, title;
        if(len > 0){
            note = pageX.cache.noteList.shift();
            if(note.code == "archiveNote"){
                title = cmp.i18n("collaboration.pighole.alert.archiveTitle");
            }
            _alert(note.msg, _close, title);
        }else{
            _gotoList();
        }
    }
}


/**
 * 设置意见内容
 */
function _setCommentValue(v, setDom){
    
    if(setDom === true){
        _$("#content").value = v;
    }
    
  //发送请求之前
    var _commentold = CollUtils.getTextDealComment("#content");
    try{
    	var paramData = {};
    	var emojiUtil = cmp.Emoji();
    	pageX.cache.postData.content = emojiUtil.EmojiToString(_commentold);
    }catch(e){
    	pageX.cache.postData.content = _commentold;
    }
    
    //at信息
    pageX.cache.postData.atWhoSelected = _mergeAtWho(pageX.cache.postData.content)
}


/**
 * 执行数据提交
 * @param type
 */
function exeSubmitData(type){
    
    //重复提交校验
    if(pageX.cache.isSubmitting && pageX.actionType == type){
        console.warn("重复执行:" + type);
        return;
    }
    
    //不同意时， 会有操作类型切换， 进行记录
    pageX.actionType = type;
    
    var actions = ["actionSubmit", "actionZcdb", "actionReturnSummary", 
                       "actionTerminateSummary", "actionRepealSummary", 
                       "actionStepBackToTargetNode", "actionSpecifiesReturn", 
                       "actionForward", "actionTransferSummary"];
    
    var backActions = ["actionReturnSummary", "actionTerminateSummary",
                         "actionRepealSummary", "actionStepBackToTargetNode", "actionSpecifiesReturn"];
    
    if(CollUtils.isInArray(actions, type)){
        
        if(window[type]){
            
            if("actionZcdb" != type && "actionForward" != type){
                
                //处理时必须填写意见 
                if(!!summaryBO.pageConfig.forceComment 
                        || (pageX.cache.postData.attitude == "collaboration.dealAttitude.disagree"
                               && summaryBO.pageConfig.forceCommentWhenDisagree)
                        || (summaryBO.pageConfig.forceCommentWhenCancel && CollUtils.isInArray(backActions, type))) {
                    
                    if(_isCommentBlank()){
                        return;
                    }
                }
            }
            
            
            
            //启动提交, 统一设置有问题， 比如核定选择后重新执行
            //_startSubmitting();
            
            //获取意见数据
            _setCommentValue();
            if(type == "actionSubmit"){
            	if(summaryBO.content && summaryBO.content.hasOffice){
            		cmp.notification.confirm(cmp.i18n("collaboration.page.lable.hasOffice.dealTip"),function(e){ //e==1是/e==0 否
            	        if(e==1){ //是
            	            var paramArgs = arguments;
            	            setTimeout(function(){
            	                window[type].apply(window, Array.prototype.slice.call(paramArgs, 1));
            	                paramArgs = null;
            	            }, 50);
            	        }else{
            	        	return;  
            	        }
            	    },null, [ cmp.i18n("collaboration.page.lable.button.cancel"), cmp.i18n("collaboration.page.lable.button.continue")], null, null, 0);
            	}else{
            		window[type].apply(window, Array.prototype.slice.call(arguments, 1));
            	}
            }else{
            	window[type].apply(window, Array.prototype.slice.call(arguments, 1));
            }

        }else{
            _alert(cmp.i18n("collaboration.tip.noFunction") + type);
        }
    }else{
        _alert(cmp.i18n("collaboration.tip.unknownOperation") + type);
    }
}

/**
 * 移交
 */
function actionTransferSummary(){
    
    CollUtils.mask(true);//添加蒙层
    
    _lockAction(function(lockRet){
        
        CollUtils.mask(false);//移除蒙层
        
        if(lockRet){
            var user = summaryBO.currentUser;
            
            //选人界面调用
            cmp.selectOrg("select_org_1_" + (new Date()).getTime(), {
                "type":2,
                "flowType" : 2,
                "label" : ["dept","org","extP", "vjOrg"],
                "directDepartment" : false,
                "flowOptsChange" : true,
                lightOptsChange : false,//轻表单模式选人
                fillBackData:[],//初始化数据
                jump:false,
                excludeData:[{"id":user.id,"name":user.name,"type":"Member","disable":true}],
                closeCallback: function(){
                    _stopSubmitting();
                },
                maxSize:1,
                minSize:1,
                accountID:"",
                selectType:'member',
                permission : true,
                callback: function(datas){
                    
                    var result = cmp.parseJSON(datas);
                    var type = result.orgResultType;
                    
                    var orgMembers, userId;
                    
                    if(orgMembers = result.orgResult){
                        for(var i = 0, len = orgMembers.length; i < len; i++){
                            //返回数据是字符串
                            var d = null;
                            if(typeof orgMembers[i] === "string"){
                                d = cmp.parseJSON(orgMembers[i]);
                            }else{
                                d = orgMembers[i];
                            }
                            userId = d.id;
                        }
                    }
                    _exeTransfer(userId);
                }
            });
        }
    });
}

/**
 * 执行移交
 * @param id 人员ID
 */
//移交回调 addby libing
function _exeTransfer(userId){
    _startSubmitting();
    function exeTransferSubmit(){
        if(userId){
			pageX.cache.postData.content = CollUtils.getTextDealComment("#content");
			pageX.cache.postData.affairId = summaryBO["summary"].affairId;
			pageX.cache.postData.transferMemberId = userId;
			
			//at信息
			pageX.cache.postData.atWhoSelected = _mergeAtWho(pageX.cache.postData.content)
			
			saveContentConfirm(function(modifyFlag){
				pageX.cache.postData.modifyFlag = modifyFlag;
    			$s.EdocResource.newTransfer({},pageX.cache.postData,errorBuilder({
    				success : function(result) {
    					_close(result);
    				},
    				error : function(){
    					_stopSubmitting();
    				}
    			}));
			},false);
        }else{
            _stopSubmitting();
        }
    }
    
    /*'该操作不能恢复，是否进行移交操作？*/
    var _cofirmHtml  = cmp.i18n("collaboration.page.notrollback.confirm.label", [cmp.i18n("collaboration.page.lable.button.transfer")]);
        
    cmp.notification.confirm(_cofirmHtml,function(e){ //e==1是/e==0 否
        if(e==1){ //是
            setTimeout(exeTransferSubmit, 50);
        }else{
            _stopSubmitting();
        }
    },null, [ cmp.i18n("collaboration.page.lable.button.cancel"), cmp.i18n("collaboration.page.dialog.OK") ],null,null,0);
    
}

/**
 * 转发
 */
function actionForward(){
    var pageParams = {
        "summaryId" : summaryBO["summary"].id,
        "affairId" : summaryBO["summary"].affairId,
        "defPolicy" : summaryBO["defPolicy"],
        'accountId':summaryBO["summary"].accountId,
        "cache_subfix" : pageX.winParams.cache_subfix,
        "WebviewEvent" : WebEvents.M3_EVENT_COMMENT + pageX.winParams.cache_subfix,
        //"backIndex" : summaryBO.backIndex + 1,
        "parentX":{
            "openFrom": "summary"
        }};

    //待发的时候转发协同该属性引起报错 跳转回来的时候重新加载页面加载上该属性。
    cmp.event.trigger("beforepageredirect",document);
    cmp.href.next(_collPath + "/html/colForward.html"+colBuildVersion, pageParams);
}

/**
 * 手动调用指定回退
 */
function actionSpecifiesReturn(){
	var idMap = {
		"summaryID" : summaryBO.summary.id,
		"affairID" : summaryBO.summary.affairId
	}
    //指定回退前事件
    var eventParams={
    	funName : "beforeDealspecifiesReturn",
    	data : idMap,
    	success : function(){
    		pageX.wfDesigner.specifiesReturn(function(returnInfo, submitStyleName){
    	        exeSubmitData("actionStepBackToTargetNode",returnInfo.toNodeId, returnInfo.submitStyle, returnInfo.isCircleBack);
    	    });
    	},
    	error : function(){
    		
    	}
    }
    cmp.funProxy.getter(eventParams);
}

/**
 * 环形流程指定回退
 */
function actionStepBackToTargetNode(theStepBackNodeId, submitStyle, isCircleBack, isWFTrace) {

    //在常用设置的
    if(!theStepBackNodeId && pageX.winParams.action == WorkFlowLock.SPECIFIES_RETURN){
        
        var returnInfo = pageX.winParams.returnInfo;
        
        theStepBackNodeId = returnInfo.toNodeId;
        submitStyle = returnInfo.submitStyle;
        isCircleBack = returnInfo.isCircleBack;
    }
    
     //设定状态
    _startSubmitting();
    
    var jsonSubmitCallBack = function() {
    	saveContentConfirm(function(modifyFlag){
    		var params = {};
    		pageX.cache.postData["workitemId"] = summaryBO["summary"].affairWorkitemId;
    		pageX.cache.postData["processId"] = summaryBO["summary"].processId;
    		pageX.cache.postData["caseId"] = summaryBO["summary"].caseId;
    		pageX.cache.postData["activityId"] = summaryBO["summary"].activityId;
    		pageX.cache.postData["affairId"] = summaryBO["summary"].affairId;
    		pageX.cache.postData["summaryId"] = summaryBO["summary"].id;
    		pageX.cache.postData["submitStyle"] = submitStyle;
    		pageX.cache.postData["theStepBackNodeId"] = theStepBackNodeId;
    		pageX.cache.postData["isCircleBack"] = isCircleBack;
    		
    		pageX.cache.postData["modifyFlag"] = modifyFlag;
    		$s.EdocResource.updateAppointStepBack({},pageX.cache.postData,errorBuilder({
    			success:function(){
    				_close();
    			}
    		}))
    	},false);
    };
    
   
    var _sub = function (){
    	if("20" == summaryBO["summary"].bodyType){
            var fromSubmitBack = function () {
                var options = {
                        moduleId:summaryBO["summary"].id,
                        needCheckRule:false,
                        notSaveDB:false,
                        rightId:summaryBO["summary"].rightId,
                        needSn : false
                }
                _formSubmit(options,jsonSubmitCallBack);
            }
            //先表单高级开发数，再预提交
            if(summaryBO.deeReadOnly == "1") {
                fromSubmitBack();
            } else {
                //表单开发高级
                formDevelopAdance4ThirdParty(summaryBO["summary"].bodyType,summaryBO["summary"].affairId,"stepstop",CollUtils.getTextDealComment("#content"),null,fromSubmitBack);
            }
        }else{
            jsonSubmitCallBack();
        }     
    }
    
    if(submitStyle == "0"){
        if(isWFTrace == null || typeof isWFTrace === "undefined"){
        	if(summaryBO.pageConfig.attitudeBtns == 3){
                //流程重走
                confirmOptAndWFTrace(_sub, "Return");
            }else{
                attituedeAlert(_sub, "Return");
            }
        }else{
        	pageX.cache.postData["isWFTrace"] = isWFTrace;
            _sub();
        }
    }else{
    	if(isWFTrace == null || typeof isWFTrace === "undefined"){
    		if(summaryBO.pageConfig.attitudeBtns == 3){
    			pageX.cache.postData["isWFTrace"] = "0";
                _sub();
            }else{
                attituedeAlert(_sub, "Submit");
            }
    	}else{
    		pageX.cache.postData["isWFTrace"] = "0";
            _sub();
    	}
    }
 }

/**
 * 弹出确认操作和流程追述的对话框
 * @param callBackFn
 */

function confirmOptAndWFTrace(callBackFn, action){
    
    var canTrackWorkflow = summaryBO.canTrackWorkflow;
    
    if(canTrackWorkflow == "1"){
        //模板设置成跟踪
        pageX.cache.postData["isWFTrace"] = "1";
        callBackFn();
    }else if(canTrackWorkflow == "2"){
        //模板设置不跟踪
        pageX.cache.postData["isWFTrace"] = "0";
        callBackFn();
    }else{
        
        /*'该操作不能恢复，是否进行回退操作？<br>流程追溯';*/
        var actionLable = actionI18n[action];
        var _cofirmHtml  = cmp.i18n("collaboration.page.notrollback.confirm.label", [actionLable])+"<br>"+ "<span class='trace_span'>" +cmp.i18n("collaboration.page.wftrace.label");
        _cofirmHtml+='<input id="isWFTrace" style="color:#2EAEF7" type="checkbox" class="select-put cmp-checkbox2">' + '</span>';
            
        cmp.dialog.loading(false);
        cmp.notification.confirm(_cofirmHtml,function(e){ //e==1是/e==0 否
            
            var isWfTrace = document.querySelector("#isWFTrace");
            pageX.cache.postData["isWFTrace"] = isWfTrace && isWfTrace.checked  ? "1" : "0";
            
            if(e==1){ //是
                //后续如果还有confirm框，比如修改正文后确认，会有问题
                setTimeout(callBackFn, 50);
                cmp.dialog.loading();
            } else{
                _stopSubmitting();
            }
        }, cmp.i18n("collaboration.page.dialog.note2"), [cmp.i18n("collaboration.page.lable.button.cancel"), cmp.i18n("collaboration.page.dialog.OK") ],null,null,0);
    }
    
}



//提交回调函数
function actionSubmit() {
    _dealSubmitFunc();
}


//暂存
function actionZcdb(){
    //设定状态
    _startSubmitting();
    
	//暂存待办前事件
	var idMap = {
		"summaryID" : summaryBO.summary.id,
		"affairID" : summaryBO.summary.affairId
	}
    var eventParams={
    	funName : "beforeDealSaveWait",
    	data : idMap,
    	success : function(){
    		_checkAffairValid(function(checkRet){
    	        var doZCDB = function(){
    	        	saveContentConfirm(function(modifyFlag){
    	        		var str_params = pageX.wfDesigner.getDatas();
    	        		str_params.colSummaryData = {"modifyFlag":modifyFlag};
    	        		pageX.cache.postData._json_params = cmp.toJSON(str_params);
    	        		$s.EdocResource.doZCDB(summaryBO["summary"].affairId, {}, pageX.cache.postData, errorBuilder({
    	        			success : function(result) {
    	        				if(result["error_msg"]){
    	        					_stopSubmitting();
    	        					_alert(result["error_msg"]);
    	        				}else {
    	        					if(window.summaryBO.signatureId){
    	        						var params={"signatureId":window.summaryBO.signatureId,
    	        								"documentId":summaryBO["summary"].id};
    	        						$s.Signet.updateIsignatureDocumentId({},params, errorBuilder({
    	        							success : function(ret){
    	        								_gotoList();
    	        							}
    	        						}));
    	        					}else{
    	        						_gotoList();
    	        					}
    	        				}
    	        			}
    	        		}));
    	        	},true);
    	        }
    	        if(checkRet){
    	            if("20" == summaryBO["summary"].bodyType){
    	                var fromSubmitBack = function () {
    	                    var options = {
    	                        moduleId:summaryBO["summary"].id,
    	                        needCheckRule:false,
    	                        needCheckRepeatedRecord : true,
    	                        notSaveDB:false,
    	                        rightId:summaryBO["summary"].rightId,
    	                        needSn : false
    	                    }
    	                    _formSubmit(options,doZCDB);
    	                }
    	                //先表单高级开发数，再预提交
    	                if(summaryBO.deeReadOnly == "1") {
    	                    fromSubmitBack();
    	                } else {
    	                    //表单开发高级
    	                    formDevelopAdance4ThirdParty(summaryBO["summary"].bodyType,summaryBO["summary"].affairId,"collaboration.dealAttitude.dealSaveWait",CollUtils.getTextDealComment("#content"),null,fromSubmitBack);
    	                }
    	            }else{
    	                doZCDB();
    	            }
    	            
    	        }else{
    	            _stopSubmitting();
    	        }
    	    });
    	},
    	error : function(){
    		_stopSubmitting();
    	}
    }
    cmp.funProxy.getter(eventParams);
}

/**
 * 执行撤销
 */
function actionRepealSummary(){
    //设定状态
    _startSubmitting();
    
    var idMap = {
		"summaryID" : summaryBO.summary.id,
		"affairID" : summaryBO.summary.affairId
	}
    //协同撤销前事件
    var eventParams={
    	funName : "beforeDealCancel",
    	data : idMap,
    	success : function(){
    		_lockAction(function(lockRet){
    	        if(lockRet){
    	        	var workflowCheckParam = {
    	      		   event : "BeforeCancel",
    	      		   callback : function(flag){
    	      			   if(flag){
    	      				   //撤销
    	      				   var doRepealBack = function() {
    	      					   var _sub = function(){
    	      						 saveContentConfirm(function(modifyFlag){
    	      							pageX.cache.postData.modifyFlag = modifyFlag;
    	      							 $s.EdocResource.repeal(summaryBO["summary"].affairId, {}, pageX.cache.postData, errorBuilder({
    	      								 success : function(result) {
    	      									 if(result["error_msg"]){
    	      										 _stopSubmitting();
    	      										 _alert(result["error_msg"]);
    	      									 }else {
    	      										 _gotoList();
    	      									 }
    	      								 }
    	      							 })); 
    	      						 },false);
    	      					   } 
    	      					   confirmOptAndWFTrace(_sub, "Cancel");
    	      				   }
    	      				   if(summaryBO.deeReadOnly == "1") {
    	      					   doRepealBack();
    	      				   } else {
    	      					   //表单开发高级
    	      					   formDevelopAdance4ThirdParty(summaryBO["summary"].bodyType,summaryBO["summary"].affairId,"repeal",CollUtils.getTextDealComment("#content"),null,doRepealBack);
    	      				   }
    	      			   }else{
    	      				 _stopSubmitting_workflow();
    	      			   }
    	      		   },
    	      		   formAppId : summaryBO.workflowCheckParam.formAppId,
    	      		   formId : summaryBO.workflowCheckParam.formId,
    	      		   formOperationId : summaryBO.workflowCheckParam.formOperationId
    	             };
    	        	pageX.wfDesigner.executeWorkflowBeforeEvent(workflowCheckParam);
    	        }
    	    });
    	},
    	error : function(){
    		_stopSubmitting();
    	}
    }
    cmp.funProxy.getter(eventParams);
}

/**
 * 执行终止
 */
function actionTerminateSummary(){
	var idMap = {
		"summaryID" : summaryBO.summary.id,
		"affairID" : summaryBO.summary.affairId
	}
	//协同终止前事件
    var eventParams={
    	funName : "beforeDealstepstop",
    	data : idMap,
    	success : function(){
    	    
    	  //设定状态
            _startSubmitting();
          //先展示态度的弹出框
           var lockAtion= function(lockRet){
                if(lockRet){
                    cmp.notification.confirm(cmp.i18n("collaboration.alert.confirm.terminate.msg"),function(e){ //e==1是/e==0 否
                        if(e==1){ //是
                            var workflowCheckParam = {
                                    event : "BeforeStop",
                                    callback : function(flag){
                                        if(flag){
                                            //终止协同
                                            var doTerminate = function(){
                                                saveContentConfirm(function(modifyFlag){
                                                    var pObj =  pageX.cache.postData;
                                                    pObj.caseId = summaryBO["summary"].caseId;
                                                    pObj.modifyFlag = modifyFlag;
                                                    $s.EdocResource.newStepStop(summaryBO["summary"].affairId, {}, pObj, errorBuilder({
                                                        success : function(result) {
                                                            
                                                            if(result["error_msg"]){
                                                                _stopSubmitting();
                                                                _alert(result["error_msg"]);
                                                            }else {
                                                                _gotoList(); 
                                                            }
                                                        }
                                                    }));
                                                },false);
                                            }
                                            if("20" == summaryBO["summary"].bodyType){
                                                var fromSubmitBack = function () {
                                                    var options = {
                                                            moduleId:summaryBO["summary"].id,
                                                            needCheckRule:false,
                                                            notSaveDB:false,
                                                            rightId:summaryBO["summary"].rightId,
                                                            needSn : false
                                                    }
                                                    _formSubmit(options,doTerminate);
                                                }
                                                //先表单高级开发数，再预提交
                                                if(summaryBO.deeReadOnly == "1") {
                                                    fromSubmitBack();
                                                } else {
                                                    //表单开发高级
                                                    formDevelopAdance4ThirdParty(summaryBO["summary"].bodyType,summaryBO["summary"].affairId,"stepstop",CollUtils.getTextDealComment("#content"),null,fromSubmitBack);
                                                }
                                            }else{
                                                doTerminate();
                                            }
                                        }else{
                                            _stopSubmitting_workflow();
                                        }
                                    },
                                   formAppId : summaryBO.workflowCheckParam.formAppId,
                                   formId : summaryBO.workflowCheckParam.formId,
                                   formOperationId : summaryBO.workflowCheckParam.formOperationId
                                };
                                pageX.wfDesigner.executeWorkflowBeforeEvent(workflowCheckParam);
                        }else{
                            _stopSubmitting();
                        }
                    },null, [ cmp.i18n("collaboration.page.lable.button.cancel"), cmp.i18n("collaboration.page.dialog.OK")],null,null,0);
                }
            }
            if(summaryBO.pageConfig.attitudeBtns == 3){
                _lockAction(lockAtion);
            }else{
                attituedeAlert(lockAtion, "stepStop");
            }
    	},
    	error : function(){
    		_stopSubmitting();
    	}
    }
    cmp.funProxy.getter(eventParams);
}

/**
 * 回退协同
 */
function actionReturnSummary(){
    //设定状态
    _startSubmitting();
    
	var idMap = {
		"summaryID" : summaryBO.summary.id,
		"affairID" : summaryBO.summary.affairId
	}
	//协同回退前事件
    var eventParams={
    	funName : "beforeDealstepback",
    	data : idMap,
    	success : function(){
    		//加锁
    	    _lockAction(function(lockRet){
    	        
    	        if(lockRet){
    	            var doStepBack = function () {
    	                _checkAffairValid(function(checkRet){
    	                    if(checkRet) {
    	                        
    	                    	var workflowCheckParam = {
    	                 		   event : "BeforeStepBack",
    	                 		   callback : function(flag){
    	                 			   if(flag){
    	                 				   //回退协同
    	                 				   var _sub = function (){
    	                 					  saveContentConfirm(function(modifyFlag){
    	                 		        		pageX.cache.postData.modifyFlag = modifyFlag;
    	                 						  $s.EdocResource.stepBack(summaryBO["summary"].affairId, {}, pageX.cache.postData, errorBuilder({
    	                 							  success : function(result) {
    	                 								  if(result["error_msg"]){
    	                 									  _stopSubmitting();
    	                 									  _alert(result["error_msg"]);
    	                 								  }else {
    	                 									  _gotoList();
    	                 								  }
    	                 							  }
    	                 						  }));
    	                 					  },false);
    	                 				   } 
    	                 				   
    	                 				   //先展示态度的弹出框
                                           if(summaryBO.pageConfig.attitudeBtns == 3){
                                               confirmOptAndWFTrace(_sub, "Return") ;
                                           }else{
                                               attituedeAlert(_sub, "Return");
                                           }
    	                 			   }else{
    	                 				  _stopSubmitting_workflow();
    	                 			   }
    	                 		   },
    	                 		   formAppId : summaryBO.workflowCheckParam.formAppId,
    	                 		   formId : summaryBO.workflowCheckParam.formId,
    	                 		   formOperationId : summaryBO.workflowCheckParam.formOperationId
    	                        };
    	                    	pageX.wfDesigner.executeWorkflowBeforeEvent(workflowCheckParam);
    	                    }
    	                });
    	            }
    	            if(summaryBO.deeReadOnly == "1") {
    	                doStepBack();
    	            } else {
    	                //表单开发高级
    	                formDevelopAdance4ThirdParty(summaryBO["summary"].bodyType,summaryBO["summary"].affairId,"stepBack",CollUtils.getTextDealComment("#content"),null,doStepBack);
    	            }
    	        }
    	    });
    	},
    	error : function(){
    		_stopSubmitting();
    	}
    }
    cmp.funProxy.getter(eventParams);
}

function _dealSubmitFunc(){
	//是否弹出 不同意的
    if(pageX.cache.postData.attitude == "collaboration.dealAttitude.disagree"){ //当态度为"不同意"时做的一些判断
        
    	if(summaryBO["currentPolicy"].id != "newsaudit" && summaryBO["currentPolicy"].id != "bulletionaudit"){
    		var optionalActions = summaryBO.pageConfig.customAction || "";    		
    		var subState = summaryBO["summary"].affairSubState;
        	
    		var actionLable = {
    		        "Continue" : cmp.i18n("collaboration.page.lable.button.continue"),
    		        "Return" : cmp.i18n("collaboration.page.lable.button.return"),
    		        "Terminate" : cmp.i18n("collaboration.page.lable.button.terminate"),
    		        "Cancel" : cmp.i18n("collaboration.page.lable.button.cancel1")
    		}
    		var actionSort = ["Continue"];
    		if(subState != '15' && subState != '16' && subState !='17' && !summaryBO.inInSpecialSB) {
                actionSort.push("Return");
            }
    		actionSort = actionSort.concat(["Terminate","Cancel"])
    		
    		
    		var items = [];
    		var ops = optionalActions.split(",");
    		if(ops[0].length>0){
    			ops.push("Continue");
    		}
    		for(var i = 0; i < actionSort.length; i++){
    		    
    		    if(CollUtils.isInArray(ops, actionSort[i])){
    		        var toAdd = false;
    		        if("Continue" == actionSort[i]){
    		            toAdd = true;
    		        }else if(_hasPermissions(summaryBO.pageConfig.nodeActions, actionSort[i])){
	                    toAdd = true;
    		        }
    		        if(toAdd){
    		            items.push({key:actionSort[i], name : actionLable[actionSort[i]]});
    		        }
    		    }
    		}
            
            //节点权限没有继续、回退、撤销、终止,系统不会弹出确认框，直接可以提交成功
            if (items.length > 0){ 
            	cmp.dialog.actionSheet(items, cmp.i18n("collaboration.page.lable.button.cancel"),function (data){
            		//from为： dealSummary 提交  returnSummary 回退 terminateSummary 终止 repealSummary 撤销
              		if (data.key== "Continue") {
              		  archivePigeonholeFn();
              		} else {
              		    pageX.currentAction = ACTION_LOCK_CODE[data.key];
              		    if (data.key == "Return") { //回退
              		        exeSubmitData("actionReturnSummary");
              		    } else if (data.key == "Terminate") { //终止
              		        exeSubmitData("actionTerminateSummary");
              		    } else if (data.key == "Cancel") { //撤销
              		        exeSubmitData("actionRepealSummary");
              		    }
              		} 
            	});
            } else {
                archivePigeonholeFn();
            }
    	}else{
    	    archivePigeonholeFn();
    	}
		
    } else {
        archivePigeonholeFn();
    }
}

/**
 * 提交协同
 */
function _dealSubmit(){
    //设定状态
    _startSubmitting();
   
    var idMap = {
		"summaryID" : summaryBO.summary.id,
		"affairID" : summaryBO.summary.affairId
	}
	//协同提交前事件
    var eventParams={
    	funName : "beforeDealSubmit",
    	data : idMap,
    	success : function(){
    		//发起人提交附言
    	    _checkAffairValid(function(checkRet){
    	        if(checkRet){
    	            
    	            var successCallBack = function(){
    	                
    	                //预提交成功或者自由协同提交方法
    	                function tempSubmit1(){
    	                    
    	                    var dofinish = function(){
    	                        
    	                        pageX.cache.postData._json_params = cmp.toJSON(pageX.wfDesigner.getDatas());
    	                        
    	                        if(window.summaryBO.signatureId){//保存签章数据
    	                            var params={"signatureId":window.summaryBO.signatureId,
    	                                    "documentId":summaryBO["summary"].id};
    	                            $s.Signet.updateIsignatureDocumentId({},params, errorBuilder({
    	                                success : function(ret){
    	                                    
    	                                }
    	                            }));
    	                        }
    	                        saveContentConfirm(function(modifyFlag){
    	                            var str_params = pageX.wfDesigner.getDatas();
    	                        	str_params.colSummaryData = {"modifyFlag":modifyFlag}; 
    	                        	if(window.summaryBO.chooseOpinionType){
    	                        		str_params.colSummaryData["chooseOpinionType"] = window.summaryBO.chooseOpinionType;
    	                        	}
    	                            str_params.comment_deal = {
        	                                "extAtt1":pageX.cache.postData.attitude,
        	                                "content":pageX.cache.postData.content
        	                            };
    	                            pageX.cache.postData._json_params = cmp.toJSON(str_params);
									 pageX.cache.postData.xbIds = str_params.workflow_definition.xbIds;
;
    	                            //处理协同
    	                            $s.EdocResource.newEdocSummaryFinishWorkItem(summaryBO["summary"].affairId, {},pageX.cache.postData, errorBuilder({
    	                                success : function(result) {
    	                                    _close(result);
    	                                }
    	                            }));
    	                        },true);
    	                    }
    	                    
    	                    function _doSaveFormData(){
    	                        
    	                    //继续调用转圈
    	                        cmp.dialog.loading();
    	                        
    	                          var isFormReadOnly = summaryBO["currentPolicy"].id =='inform' || summaryBO.deeReadOnly == "1";
    	                          
    	                          if("20" == summaryBO["summary"].bodyType  && !isFormReadOnly ){
    	                              //3：表单正式入库
    	                              var options = { 
    	                                      moduleId:summaryBO["summary"].id,
    	                                      needCheckRule:false,
    	                                      notSaveDB:false,
    	                                      allowQRScan : summaryBO["summary"].canScanCode =='1',
    	                                      needSn : true,
    	                                      submitSource : _getFormType()
    	                              }
    	                              cmp.sui.submit(options,function(err,data){
    	                                  if(err || data.success =="false"){
    	                                      //1：:停止提交
    	                                      _stopSubmitting();
    	                                      //2: 缓存页面数据并返回详细界面
    	                                      //cmp.event.trigger("beforepageredirect",document);
    	                                  }else{
    	                                      //4：协同的finish逻辑
    	                                      if(data.snMsg){
    	                                          pageX.cache.noteList.push({
    	                                              "code" : "formSnMsg",
    	                                              "msg" : data.snMsg
    	                                          });
    	                                      }
    	                                      dofinish();
    	                                  }
    	                              });
    	                          }else{
    	                              dofinish();
    	                          }
    	                    }
    	                    //
    	                    if(summaryBO["currentPolicy"].id == "newsaudit" 
    	                        || summaryBO["currentPolicy"].id == "bulletionaudit"){
    	                        
    	                        newsAndbulletinIssue(_doSaveFormData);
    	                    }else{
    	                        _doSaveFormData();
    	                    }
    	                }
    	                
    	                var tempId = summaryBO.summary.templateId;
    	                var tempIsTemplate = !(!tempId || tempId == '' || tempId == "0" || tempId == "-1");
    	                
    	                //自由协同
    	                if(!tempIsTemplate){
    	                    
    	                    WorkFlowDesignerUtil.lockH5Workflow(summaryBO.summary.processId, 14, function(ret) {
    	                        if(ret) {
    	                            tempSubmit1();
    	                        }else{
    	                            _stopSubmitting();
    	                        }
    	                    });
    	                    
    	                }else{
    	                    var workflowCheckParam = {
    	                            event : "BeforeFinishWorkitem",
    	                            callback : function(flag){
    	                                if(flag){
    	                                    var currentWorkItemIsInSpecial = (summaryBO["summary"].affairSubState == '15' 
    	                                        || summaryBO["summary"].affairSubState == '16' 
    	                                            || summaryBO["summary"].affairSubState == '17');
    	                                    
    	                                    //2：工作流预提交
    	                                    pageX.wfDesigner.preSubmit({
    	                                        contentData : [],
    	                                        onPop : function(){
    	                                            //组件层级管理，需要把这个影藏
    	                                            cmp.dialog.loading(false);
    	                                        },
    	                                        callback : function(preSubmitResult){
    	                                            if(preSubmitResult["result"] == "true"){
    	                                                tempSubmit1();
    	                                            }else{
    	                                                _stopSubmitting();
    	                                            }
    	                                        },
    	                                        "currentWorkItemIsInSpecial":currentWorkItemIsInSpecial,
    	                                    })
    	                                }else{
    	                                    _stopSubmitting();
    	                                }
    	                            },
    	                            formAppId : summaryBO.workflowCheckParam.formAppId,
    	                            formId : summaryBO.workflowCheckParam.formId,
    	                            formOperationId : summaryBO.workflowCheckParam.formOperationId
    	                        };
    	                        pageX.wfDesigner.executeWorkflowBeforeEvent(workflowCheckParam);
    	                }
    	            }
    	            if("20" == summaryBO["summary"].bodyType){
    	            	
    	            	var deeCallBack = function(){
    	            		 //先表单高级开发数，再预提交
        	                if(summaryBO.deeReadOnly == "1") {
        	                	successCallBack();
        	                } else {
        	                    // V50_SP2_NC业务集成插件_001_表单开发高级
        	                    var __attitudeArray = pageX.cache.postData.attitude || "collaboration.dealAttitude.haveRead";
        	                    //表单开发高级
        	                    formDevelopAdance4ThirdParty(summaryBO["summary"].bodyType,summaryBO["summary"].affairId,__attitudeArray,CollUtils.getTextDealComment("#content"),null,successCallBack);
        	                }
    	            	}
    	            	
	            	   var options = {
 	                        moduleId:summaryBO["summary"].id,
 	                        needCheckRule:true,
 	                        notSaveDB:true,
 	                        needSn : false
 	                    }
	            	   try{
	                         _formSubmit(options, deeCallBack);
	                     }catch(e){
	                         _alert("There was an error on this page,message:"+e.message);
	                     }
    	            }else{
    	                successCallBack();
    	            }
    	        }else{
    	            _stopSubmitting();
    	        }
    	    });
    	},
    	error : function(){
    		_stopSubmitting();
    	}
    }
    cmp.funProxy.getter(eventParams);
}

function _formSubmit(options,successCallBack){
	
	if(summaryBO["currentPolicy"].id =='inform'
	    || summaryBO.deeReadOnly == "1"){
	    
		successCallBack(); 
		return;
	}
	
	 //组装参数
	var options = { 
			moduleId:summaryBO["summary"].id,
			needCheckRule:options.needCheckRule,
			notSaveDB:options.notSaveDB,
			rightId:summaryBO["summary"].rightId,
			allowQRScan : summaryBO["summary"].canScanCode =='1',
            needSn : options.needSn,
            submitSource : _getFormType()
	}
	
	cmp.sui.submit(options,function(err,data){
		if(err || data.success =="false"){
				//1：:停止提交
				_stopSubmitting();
				_goBackToSummary();
		}else{
			successCallBack();
		}
	});
}

//处理后归档
function archivePigeonholeFn(){
    
	if(pageX.cache.postData.Archive){
	    
		//选择了归档。回调获取归档的目录
		docPigehole4Edoc("",function (_result){
			if(_result && _result.msg=="OK"){
				pageX.cache.postData.archiveValue = _result.id;
				
				var params = {
						affairId : summaryBO["summary"].affairId,
			            destFolderId : _result.id
			    }
				//校验同一个人是否将协同归档到同一个目录
				$s.Coll.getIsSamePigeonhole({},params,errorBuilder({
					success: function(result){
			            if(result["retMsg"]){
			                cmp.notification.confirm(result["retMsg"],function(e){ //e==1是/e==0 否
			        	        if(e==1){ //是
			        	            pageX.cache.noteList.push({
                                        "code" : "archiveNote",
                                        "msg" : cmp.i18n("collaboration.pighole.alert.archiveNote", [_result.fullPath])
                                    });
			        	            _dealSubmit();
			        	        }else{
			        	        	return;  
			        	        }
			        	    },null, [ cmp.i18n("collaboration.page.lable.button.cancel"), cmp.i18n("collaboration.page.dialog.OK")],null,null,0);
			            }else{
			                pageX.cache.noteList.push({
                                "code" : "archiveNote",
                                "msg" : cmp.i18n("collaboration.pighole.alert.archiveNote", [_result.fullPath])
                            });
			                _dealSubmit();
			            }
			        }
				}));
			}else{//点取消
				pageX.cache.postData.archiveValue = "";
				_$("#docPigeonhole").classList.remove('cmp-active');
				for(var n=0,len = pageX.cache.noteList.length; n < len; n++){
				    var note = pageX.cache.noteList[n];
				    if(note.code == "archiveNote"){
				        pageX.cache.noteList.splice(n, 1);
				        break;
				    }
				}
				return;
			}
		});
	}else{
	 if(window["summaryBO"].isAlertStepbackDialog){
	    var _cofirmHtml  = "<span id='attitudeSpan' class='trace_span'>";
	    
	    _cofirmHtml+='<input id="theOne" name="attitude" style="color:#2EAEF7" type="radio" class="select-put cmp-radio2" value="1">' +"保留最后一次意见</br>";
	    _cofirmHtml+='<input id="theAll" name="attitude" style="color:#2EAEF7" type="radio" class="select-put cmp-radio2" value="2" checked="checked">' +"保留所有意见" + '</span>';
	     
	    cmp.notification.confirm(_cofirmHtml,function(e){ //e==1是/e==0 否
	        if(e==1){ //是
	        	var chooseOpinionType=_$("input[name = 'attitude']:checked").value;
	        	window.summaryBO.chooseOpinionType = chooseOpinionType;
	        	_dealSubmit();
	        }else{
	        	return;
	        }
	    },null, [ cmp.i18n("collaboration.page.lable.button.cancel"), cmp.i18n("collaboration.page.dialog.OK") ],null,null,0);
	    
	
      } else {
    	  _dealSubmit(); 
      } 
	}
}

//是否是转新闻或转公告
function newsAndbulletinIssue(callbackFn){
    var _type = "";
	if(summaryBO["currentPolicy"].id == "newsaudit"){//新闻审批发布并通过
	    _type = "newsIssue";
	}else if(summaryBO["currentPolicy"].id == "bulletionaudit"){//公告审批发布并通过
	    _type = "bulIssue";
	}
	
	if(_type != ""){
	    var _params = {
                "affairId":summaryBO["summary"].affairId,
                "summaryId":summaryBO["summary"].id,
                "bodyType":summaryBO["summary"].bodyType,
                "rightId":summaryBO["summary"].rightId}
	    
        window[_type].issue.init("issueCol",_params,function (ret){
            if(ret === true){
                callbackFn();
            }else{
                _stopSubmitting();
            }
        });
	}else{
	    callbackFn();
	}
	
}

/*
 * 校验意见是否为空
 */
function _isCommentBlank(){
    
    var ret = false;
    if((CollUtils.getTextDealComment("#content")).trim() == ""){
        _alert(cmp.i18n(("collaboration.action.alert.comment_null_2")));
        ret = true;
    }
    return ret;
}

//检查affair状态是否正常
function _checkAffairValid(callback){
    var params = {
            affairId : summaryBO["summary"].affairId
    }
    $s.Coll.checkAffairValid(params, errorBuilder({
        success: function(result){
            if(result["error_msg"]){
                callback(false);
                _alert(result["error_msg"], _gotoList);//提示
            }else{
                callback(true);
            }
        },
        error : function(result){
        	//网络问题
        	if(result.code == "-1001"){
        	  	//解除各按钮的绑定
        	  	_removeEvent();
        	}
        }
    }))
}

//开始提交
function _startSubmitting(){
    cmp.dialog.loading();
    pageX.cache.isSubmitting = true;
}

//结束提交
function _stopSubmitting(){
    if(pageX.currentAction){
        WorkFlowDesignerUtil.unLockH5Workflow(summaryBO["summary"].processId, pageX.currentAction);
        pageX.currentAction = null;
    }
    cmp.dialog.loading(false);
    pageX.cache.isSubmitting = false;
    pageX.cache.noteList = [];
}

function _lockAction(callback){
    if(pageX.currentAction){
        WorkFlowDesignerUtil.lockH5Workflow(summaryBO["summary"].processId, pageX.currentAction, function(ret) {
            if(ret) {
                callback(true);
            }else{
                callback(false);
                _stopSubmitting_workflow();
            }
        });
    }else{
        callback(true);
    }
}

/**
 * 流程校验接口所需撤销方法
 */
function _stopSubmitting_workflow(){
	pageX.currentAction = null;
    _stopSubmitting();
}

/**
 * 表单需要知道当前是什么状态
 * @returns {String}
 */
function _getFormType(){
    
    if(summaryBO.isLightForm){
        return "mobile";
    }else{
        return "pc";
    }
}

/**
 * 修改正文提示
 */
function saveContentConfirm(saveCallback,isSave){
	var editFlag = window.summaryBO.editParam ? window.summaryBO.editParam.hasEditContent : false;
	if(editFlag){
		if(isSave){//暂存和提交默认保存正文，不提示
			ContentEdit.uploadToServer(function(){
				saveCallback("1");
			});
		}else{
			cmp.notification.confirm(cmp.i18n("collaboration.edit.office.content.issave"),function(e){ //e==1是/e==0 否
				if(e==1){ //是
					ContentEdit.uploadToServer(function(){
						saveCallback("1");
					});
				}else{
					saveCallback("0");
				}
			},null, [ cmp.i18n("collaboration.page.lable.button.cancel"), cmp.i18n("collaboration.page.dialog.OK")],null,null,0);
		}
	}else{
		saveCallback("0");
	}
}
function _doZcdb(){
	if(pageX.cache.postData.Archive){
		_alert(cmp.i18n("collaboration.zcdb.archive"),function(){
			exeSubmitData("actionZcdb");
		});
	}else{
		exeSubmitData("actionZcdb");
	}
}
function _doSubmit(){
	exeSubmitData("actionSubmit");
}

function _removeEvent(){
	_$("#zcdbBtn").removeEventListener("tap", _send);
	_$("#submitBtn").removeEventListener("tap", _doSubmit);
}

/*
*显示节点态度的提示框
*/
function attituedeAlert(callbackFn,action){
    /*节点态度</br>已阅 同意 不同意*/
        var _cofirmHtml  = "<span id='attitudeSpan' class='trace_span'>";
        if(summaryBO.pageConfig.attitudeBtns == 1){
            _cofirmHtml+='<input id="haveRead" name="attitude" style="color:#2EAEF7" type="radio" class="select-put cmp-radio2" value="collaboration.dealAttitude.haveRead">'+cmp.i18n("collaboration.page.lable.att_readed");
        }
        _cofirmHtml+='<input id="agree" name="attitude" style="color:#2EAEF7" type="radio" class="select-put cmp-radio2" value="collaboration.dealAttitude.agree">' +cmp.i18n("collaboration.page.lable.att_agree");
        _cofirmHtml+='<input id="disagree" name="attitude" style="color:#2EAEF7" type="radio" class="select-put cmp-radio2" value="collaboration.dealAttitude.disagree" checked="checked">' +cmp.i18n("collaboration.page.lable.att_disagree") + '</span>';

        var attitude = pageX.cache.postData.attitude;
        cmp.dialog.loading(false);
        cmp.notification.confirm(_cofirmHtml,function(e){ //e==1是/e==0 否
            if(e==1){ //是
                var rv = _$("input[name='attitude']:checked").value;
                pageX.cache.postData.attitude = rv;
                if(action == 'Return'){
                    confirmOptAndWFTrace(callbackFn,action);
                }
                if(action == 'stepStop'){
                    _lockAction(callbackFn);
                }
                if(action == 'Submit'){
                    pageX.cache.postData["isWFTrace"] = "0";
                    callbackFn();
                }
            } else{
                _stopSubmitting();
            }
        }, cmp.i18n("collaboration.page.dialog.note3"), [cmp.i18n("collaboration.page.lable.button.cancel"), cmp.i18n("collaboration.page.dialog.OK") ],null,null,0);
}

/*******为别人提供的接口 begin*******/
/*	获取意见类型
 return String
	collaboration.dealAttitude.haveRead   已阅
	collaboration.dealAttitude.agree      同意
	collaboration.dealAttitude.disagree   不同意
*/
function getOpinion(){
	return pageX.cache.postData.attitude;
}
/*	获取意见内容
	return String
 */
function getOpinionContent(){
	var content = CollUtils.getTextDealComment("#content");
	var emojiUtil = cmp.Emoji();
	return emojiUtil.EmojiToString(content);
}
/*	获取节点类型
	return Object
	id:key
	name:描述
*/
function getCurrentPolicy(){
	return summaryBO.currentPolicy;
}
/*******为别人提供的接口 end*******/

function _continueDo(){
    //跳转到续办界面
    cmp.event.trigger("beforepageredirect", document);//跳转到续办界面之前保存一下处理界面的数据
    var nextURL = "/html/details/continueDo.html";
    cmp.href.next(_edocPath + nextURL , summaryBO);
}
//从续办界面返回回来,继续执行提交操作
function _backFromContinue(){
    var backParam=cmp.href.getBackParam();
    if(backParam!=null){
        //是否从续办界面返回
        var isBackFromContinnue=backParam.isBackFromContinnue;
        if(isBackFromContinnue){
            //是否需要续办
            var isContinnue=backParam.isContinnue;
            if(isContinnue){
                //从续办界面返回来的数据
                var backData=backParam.backData;
                if(parseInt(backData.policyIndex) < parseInt(summaryBO["summary"].returnPermissionsLength)){//需要提交返回
                    _addBackMemberToFlow(backData);
                }else{//不需要提交返回
                    _addContinueMemberToFlow(backData);
                }
            }else{
                _doSubmit();
            }
        }
    }
}

/**
 * 添加返回人到流程图中
 * @private
 */
function _addBackMemberToFlow(backData){
    var params = {}
    var members = [];
    var member = new Object();
    member.id = summaryBO["summary"].nextMember.id;//为对象增加属性
    member.name = summaryBO["summary"].nextMember.name;
    member.entityType = "Member";
    member.excludeChildDepartment = "";
    member.accountId = summaryBO["summary"].nextMember.orgAccountId;
    member.accountName = summaryBO["summary"].nextMember.orgAccountName;
    members.push(member);
    params["members"] = members;
    params["flowType"] = "1";//串发
    params["formOperationPolicy"] = "0";//由1改为了0，为了解决续办后文单权限被改变了
    params["policyId"] = summaryBO["summary"].currentPolicyId;
    params["policyName"] =summaryBO["summary"].currentPolicyName;
    params["changeType"] = "1";//1:加签，
    params["baseReadyObjectJSON"] = "";
    params["activityId"] = summaryBO["summary"].activityId;
    params["subObjectId"] =summaryBO["summary"].activityId;
    params["callback"] = function(jData){
        pageX.wfDesigner.drawWf(jData);
        pageX.wfDesigner._cacheAddNodeInfo(jData);//需要放在_setAddNodeInfo前面
        //TODO 这里可以优化， 后续的js不在解析加签信息
        pageX.wfDesigner._setAddNodeInfo(jData, false);
        //添加续办人到流程图中
        _addContinueMemberToFlow(backData);
		var size = jData.nodes.length;
    }
    pageX.wfDesigner._editWorkflowForContinueDo(params);
}

/**
 * 添加续办人到流程图中
 * @private
 */
function _addContinueMemberToFlow(backData){
    var params = {}
    var members = [];
    var member = new Object();
    member.id = backData.id;//为对象增加属性
    member.name = backData.name;
    member.entityType = backData.entityType;
    member.excludeChildDepartment = "";
    member.accountId = backData.accountId;
    member.accountName =backData.accountName;
    members.push(member);
    params["members"] = members;
    params["flowType"] = "1";//串发
    params["formOperationPolicy"] = "0";//由1改为了0，为了解决续办后文单权限被改变了
    params["policyId"] = backData.policyId;
    params["policyName"] =backData.policyName;
    params["changeType"] = "1";//1:加签，
    params["baseReadyObjectJSON"] = "";
    params["activityId"] = summaryBO["summary"].activityId;
    params["subObjectId"] =summaryBO["summary"].activityId;
    params["callback"] = function(jData){
        pageX.wfDesigner.drawWf(jData);
        pageX.wfDesigner._cacheAddNodeInfo(jData);//需要放在_setAddNodeInfo前面
        //TODO 这里可以优化， 后续的js不在解析加签信息
        pageX.wfDesigner._setAddNodeInfo(jData, false);
		var size = jData.nodes.length;
        //继续提交
        _doSubmit();
    }
    pageX.wfDesigner._editWorkflowForContinueDo(params);
}


